package pipeline

import (
	"alarm-flow/datasource"
	"alarm-flow/models"
	"alarm-flow/models/external"
	"encoding/json"
)

// RedisAlarmConfig 告警配置在 redis 缓存的数据格式
type RedisAlarmConfig struct {
	models.AlarmConfig
	Conditions []models.AlarmCondition `json:"conditions"`
}

func (rc RedisAlarmConfig) MarshalBinary() (data []byte, err error) {
	return json.Marshal(rc)
}

func SyncAlarmConfig() (err error) {
	pg := datasource.PgEngine

	allConfig := make([]models.AlarmConfig, 0)
	err = pg.Where("1=1").Find(&allConfig)
	if err != nil {
		return
	}

	allCondition := make([]models.AlarmCondition, 0)
	err = pg.Where("1=1").Find(&allCondition)
	if err != nil {
		return
	}
	mapCondition := make(map[int64][]models.AlarmCondition)
	for _, condition := range allCondition {
		if _, ok := mapCondition[condition.AlarmConfigId]; !ok {
			mapCondition[condition.AlarmConfigId] = make([]models.AlarmCondition, 0)
		}
		mapCondition[condition.AlarmConfigId] = append(mapCondition[condition.AlarmConfigId], condition)
	}

	for _, config := range allConfig {
		err = setAlarmConfig(RedisAlarmConfig{config, mapCondition[config.Id]})
		err = addMeasurementField(config.Measurement, config.Field)
	}

	return
}

// RedisInstState 实例告警指标状态
type RedisInstState struct {
	State     string `json:"state"`     // normal/alarming
	Timestamp int64  `json:"timestamp"` // 毫秒
}

func (rc RedisInstState) MarshalBinary() (data []byte, err error) {
	return json.Marshal(rc)
}

func SyncInstState() (err error) {
	pg := datasource.PgEngine

	allHost := make([]external.Instance, 0)
	err = pg.Where("model_id=1").Find(&allHost)
	if err != nil {
		return
	}

	allConfig := make([]models.AlarmConfig, 0)
	err = pg.Where("1=1").Find(&allConfig)
	if err != nil {
		return
	}

	for _, alarmConfig := range allConfig {
		for _, hostInst := range allHost {
			err = setInstState(hostInst.Id, alarmConfig.Measurement, alarmConfig.Field, "")
			if err != nil {
				return
			}
		}
	}

	return
}

// RedisPushConfig todo
type RedisPushConfig struct {
	PushWindowSize int64 `json:"push_window_size"`
}

func SyncPushConfig() (err error) {
	//pg := datasource.PgEngine
	//redisCli := datasource.RedisCli

	// todo
	return nil

}
